<?php


namespace app\cdkjt\controller;

use data\extend\cdkjt\Cdkjt;
use data\model\VslOrderCustom;
use data\model\VslOrderCustomSign;
use data\service\cdkjt\CdkjtService;
use think\Controller;
use think\Request;

//海关179服务注册地址
class Hgtask extends Controller
{

    private $redis;
    public function __construct(Request $request = null)
    {
        parent::__construct($request);
        $this->redis = CdkjtService::connectRedis();
    }

    //接收并保存海关请求
    public function index()
    {
        $postStr = $this->request->post('openReq');
        /*$postStr = json_encode([
            'orderNo'       =>  '20210118140215153983',
            'sessionID'     =>  'fe2374-8fnejf97-32839111',
            'serviceTime'   =>  time()
        ]);*/
        if($postStr){
            $data = json_decode($postStr,true);
            //得到的值加入redis和数据库中
            //$redis->sadd('hg_custom',$postStr);
            $this->redis->lPush(CdkjtService::$queue_customs,$postStr);           //放进查询队列
            $date = date('Y-m-d H:i:s');
            VslOrderCustom::create([
                'orderNo'       =>  $data['orderNo'],
                'sessionID'     =>  $data['sessionID'],
                'serviceTime'   =>  $data['serviceTime'],
                'createtime'    =>  $date,
                'updatetime'    =>  $date,
                'status'        =>  0,
            ]);
        }
        return json([
            'code'          =>  '10000',
            'message'       =>  '',
            'serviceTime'   =>  time()
        ]);
    }


    //消费查询队列，有数据则加入获取签名的队列
    public function getCustom(){
        while (true){
            $orderinfo = $this->redis->rPop(CdkjtService::$queue_customs);
            if($orderinfo){
                $orderinfo = json_decode($orderinfo,true);
                //转入待签名队列
                $cdkjt = new Cdkjt();
                $date = date('Y-m-d H:i:s');
                VslOrderCustomSign::create([
                    'copNo'         =>  $cdkjt->create_guid(),
                    'orderNo'       =>  $orderinfo['orderNo'],
                    'sessionID'     =>  $orderinfo['sessionID'],
                    'status'        =>  0,
                    'createtime'    =>  $date,
                    'updatetime'    =>  $date
                ]);
                $this->redis->lPush(CdkjtService::$queue_signs,$orderinfo['sessionID']);
            }else{
                break;
            }
        }

    }

    //消费待签名队列，请求公服平台签名服务获取签名数据
   /* public function getSign(){
        while (true){
            $sessionID = $this->redis->rPop(CdkjtService::$queue_signs);
            //$sessionID = 'i2df7df1610431343';
            if($sessionID){       //如果存在订单号,构造签名原始数据
                $customOrderSign = VslOrderCustomSign::where(['sessionID'=>$sessionID])->find();
                if($customOrderSign)
                {
                    $orderCustom = VslOrderCustom::where(['sessionID'=>$sessionID])->find();
                    if($orderCustom){
                        $result = $this->_buildResult($orderCustom);
                        $signInit = $result['signValue'];                       //加密原始数据
                        $orderCustom->content = base64_encode(json_encode($result));
                        $orderCustom->save();
                        //更新custom表的content
                        $signData = [
                            'signInit'      =>  $signInit,
                            'copNo'         =>  $customOrderSign->copNo,
                            //'note'          =>  \think\Config::get('cdkjt.payCode'),                         //支付企业的海关注册登记编号
                        ];
                        $cdkjtService = new CdkjtService();
                        $cdkjtService->getSign($signData);
                        //dump($rs);
                    }
                }

            }else{
                break;
            }
        }

    }*/


    //消费待上传队列，执行179订单数据上传任务
    public function uploadOrder()
    {
        while (true){
            $sessionID = $this->redis->rPop(CdkjtService::$queue_orders);
            if($sessionID)
            {
                $OrderCustom = VslOrderCustom::where(['sessionID'=>$sessionID])->find();
                if($OrderCustom){
                    $str = base64_decode($OrderCustom->content);
                    $str = htmlspecialchars_decode($str);
                    $result = json_decode($str,true);
                    $result['signValue'] = $OrderCustom->sign;          //签名替换
                    //请求179海关上传接口
                    $Jssign = new Jssign();
                    $SignRs = $Jssign->_buildResult($OrderCustom,2);
                    $SignRs['payExchangeInfoHead']['guid'] = $result['payExchangeInfoHead']['guid'];
                    $SignRs['signValue'] = $OrderCustom->sign;
                    $Cdkjt = new Cdkjt();

                    $str = json_encode($SignRs);
                    $data = $Cdkjt->uploadOrder(urlencode($str));
                    if($data['code'] == '10000'){
                        $status = 1;
                    }else{
                        $status = -1;
                    }
                    $OrderCustom->status = $status;
                    $OrderCustom->returncontent = $data['message'].':'.$data['code'];
                    $OrderCustom->updatetime = date('Y-m-d H:i:s');
                    $OrderCustom->save();
                }
            }else{
                break;
            }
        }
    }


    //将收到的公服回执消息通知到吉客云
    public function notifyjky()
    {
        $jkyNotifyUrl = \think\Config::get('jikeyun.notifyUrl');
        while (true){
            $xml = $this->redis->rPop(CdkjtService::$queue_notify);
            if($xml && $jkyNotifyUrl){
                $cdkjt = new Cdkjt();
                $cdkjt->_curl($jkyNotifyUrl,['message'=>$xml]);
            }else{
                break;
            }
        }
    }


    //执行队列方法
    public function dowork(){
        //判断是否有179查询订单，去获取签名
        $this->getCustom();
        //判断是否有成功的签名
        //$this->getSign();
        //sleep(10);
        //判断是否有待上传订单
        $this->uploadOrder();
        $this->notifyjky();
    }


}